window.onload = () => {
    
    window.btns_copy = document.querySelectorAll("button[name^=copy]");
    window.my_cards = document.querySelectorAll("div.card");
    window.img_div = document.querySelector('div[name=img-selecting]')
    window.pagination_container = document.querySelector('div#pagination')

    img_pagination(1);
}

function popup_msg(title, ...msgs) {
    $('h5.modal-title').html(title)
    if (msgs) {
        let msg_innerHtml = msgs.map(msg => `<p>${msg}</p>`).join('')
        $('div.modal-body').html(msg_innerHtml)
    }
    $('div.modal').modal()
}

function release_button() {
    let clicked_btn = document.querySelector("button[name^=copy].disabled");
    if (clicked_btn) {
        clicked_btn.classList.toggle("disabled", false);
        if (clicked_btn["name"] === "copytext") {
            clicked_btn.innerHTML = '<span class="bi bi-card-text"></span> 点击复制为文字';
        } else {
            clicked_btn.innerHTML = '<span class="bi bi-image"></span> 点击复制为图片';
        }
    };
}

function deselect_img() {
    let selected_img = document.querySelector('div.shadow-lg.border.border-primary');
    if (selected_img) {
        selected_img.classList.remove('shadow-lg', 'border', 'border-primary', 'p-1');
        selected_img.classList.toggle('p-2', true);
    }
}

function hiding_showing(node) {
    if (node.innerText === "复制图片模式") {
        node.innerText = "复制文字模式";
    } else {
        node.innerText = "复制图片模式";
    }

    for (let btn of btns_copy) {
        btn.classList.toggle("d-none");
    }
}

async function img_pagination(index) {
    try {
        let resp = await fetch(`http://${window.location.host}/img/${index}`)
        if (!resp.ok) throw new Error(resp.status)

        let data = await resp.json()
        list_imgs(data.imgs)
        pagination_container.innerHTML = data.pagination_html
    } catch (e) {
        popup_msg('出错了', '无法访问服务器, 请检查...', '可能是程序被意外关闭, 建议重新开启后再试', e)
    }
}

function list_imgs(img_urls) {
    let imgs = img_div.querySelectorAll('div[name=img-i]')
    let difference = imgs.length - img_urls.length
    if (difference > 0) {
        imgs = Array.from(imgs)
        imgs.splice(-difference).forEach(i => i.remove())
    }

    for (let i = 0; i < img_urls.length; i++) {
        //console.log('现有图片数量: ',imgs.length)
        if (i < imgs.length) {
            if (imgs[i].classList.contains('shadow-lg')) {
                deselect_img()
            }
            imgs[i].firstElementChild.setAttribute('src', img_urls[i])
        }
        else {

            let div = document.createElement('div')
            div.setAttribute('class', 'col-md-1 p-2')
            div.setAttribute('name', 'img-i')

            let img = document.createElement('img')
            img.setAttribute('src', img_urls[i])
            img.setAttribute('class', "img-fluid")
            img.setAttribute('alt', '图像未正确显示')
            img.onclick = change_bg

            div.appendChild(img)
            img_div.appendChild(div)
        }
    }
}


async function from_local_img() {
    if (!window.chrome || !'chrome' in window) {
        popup_msg('用不了',
            '该功能仅限Chrome内核浏览器, 你的浏览器不支持.',
            '推荐使用最新版的<strong>谷歌浏览器, 微软Edge浏览器, 360浏览器, 遨游浏览器...</strong>',
            '请复制下方网址, 使用上述浏览器访问:',
            `<span class="user-select-all"><strong>http://${window.location.host}</strong></span>`)
        return
    }
    // 构建一个 FormData 实例
    const formData = new FormData();

    //文件选项
    const pickerOpts = {
        types: [
            {
                description: "Images",
                accept: {
                    "image/*": [".png", ".jpeg", ".jpg"],
                },
            },
        ],
        excludeAcceptAllOption: true,
        multiple: false,
        startIn: "pictures",
    };

    // 添加一个文件
    let selection = null
    try {
        selection = await window.showOpenFilePicker(pickerOpts)
    } catch (error) {
        console.log(error)
        return
    }

    //开始转圈
    let btn_spinner = document.querySelector('button[name=from_local]')
    btn_spinner.classList.toggle('disabled', true)

    btn_spinner.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...`
    if (selection.length > 0) {
        const file = await selection[0].getFile();
        formData.append("file", file);
    }

    try {
        const response = await fetch(`http://${window.location.host}/local-img`, {
            method: "POST",
            // headers: {"Content-type": "multipart/form-data"},
            // 将 FormData 实例设置为请求正文
            body: formData,
        });

        //console.log(await response.json());
        let msg = []
        if (response.ok) {
            msg = await response.json()
        } else {
            console.log(`响应状态码${response.status}`)
            popup_msg('出错了', '服务器响应错误', `状态码: ${response.status}`, '只接受小于<strong>12MB</strong>的图片文件, 请检查')
        }

        if (msg[0] === 'ok') {
            change_bg(msg[1])
        } else if (msg.length) {
            console.log(msg[0], msg[1])
            popup_msg('出错了', msg[0], msg[1])
        }
        // 结束转圈
        btn_spinner.classList.toggle('disabled', false)
        btn_spinner.innerHTML = '选择本机图片'

    } catch (e) {
        console.error(e)
        popup_msg('出错了', e)
        btn_spinner.classList.toggle('disabled', false)
        btn_spinner.innerHTML = '选择本机图片'
    }
}

function change_bg(event) {

    let my_filename = ''

    if (event && typeof (event) === 'string') {
        my_filename = event + '?tempid=' + Math.ceil(Math.random() * 100000)
        release_button();
        deselect_img();
    } else if (event) {
        //判断图片是否已被选中(避免重复选中)
        //其实不用, 同url图片浏览器会缓存
        let img = event.target
        let img_parent = img.parentElement;
        if (img_parent.classList.contains('shadow-lg')) return;
        release_button();
        deselect_img();
        img_parent.classList.add('shadow-lg', 'border', 'border-primary', 'p-1');
        img_parent.classList.toggle('p-2', false);

        let my_url = img.currentSrc;
        my_filename = my_url.replace(window.location.href, '');
    } else return

    for (let card of my_cards) {
        let card_img = card.lastElementChild
        card_img.setAttribute('src', my_filename)
        if (card_img.classList.contains('d-none')) {
            card_img.classList.toggle('d-none')
            card.style['color'] = 'white'
            card.style['text-shadow'] = '0 0 3px #000000'
            card.classList.remove('bg-light')
            card.classList.add('bg-transparent')
        }
    }
}

function rm_bg() {
    release_button();
    deselect_img();
    for (let card of my_cards) {
        let card_img = card.lastElementChild
        if (!card_img.classList.contains('d-none')) {
            card_img.classList.toggle('d-none')
            card.removeAttribute('style')
            card.classList.remove('bg-transparent')
            card.classList.add('bg-light')
        }
    }
}

function name_tip(node) {

    if (node.getAttribute('aria-expanded') === 'false') {

        node.classList.remove('btn-outline-primary');
        node.classList.add('btn-primary');
        node.innerText = '点击收起小窗';
    } else {
        node.classList.remove('btn-primary');
        node.classList.add('btn-outline-primary');
        node.innerText = '更换背景图案';
    }
}

async function copy_blob(blob) {
    let img_item = new window.ClipboardItem({ 'image/png': blob });
    await navigator.clipboard.write([img_item]);
}

async function get_canvas(to_render) {
    /* 如果有img需要绘制, html2canvas函数会向服务器请求图片.
    因此, 须确保网络畅通, 否则会影响渲染效果 */

    try {
        let resp = await fetch(window.location.href)
        if (resp.ok) {
            return html2canvas(to_render, {
                scale: 2,
                ignoreElements: e => e.tagName === 'BUTTON',
                onclone: (doc, e) => {
                    e.style['border-style'] = 'none'
                    e.lastElementChild.style['height'] = '100.2%'
                },
            })
        }
        else throw new Error(`状态: resp.status`);

    } catch (e) {
        popup_msg('出错了', '无法访问服务器, 请检查...', '可能是程序被意外关闭, 建议重新开启后再试', e)
        return false
    }
}

async function save_all_cards(zip_name) {
    // tag a的data-dismiss="modal"属性有问题, 无法激活链接
    // 只能手动dismiss
    $('div#exampleModal').modal('hide')

    let btn_dlall = document.querySelector('button#dlall')

    //开始转圈
    let original_name = btn_dlall.innerHTML
    btn_dlall.classList.toggle('disabled', true)
    btn_dlall.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 文件下载中...`

    try {
        const zip = new JSZip()

        for (let card of my_cards) {
            let a_canvas = await get_canvas(card)
            if (!a_canvas) {
                // 建议throw异常
                btn_dlall.classList.toggle('disabled', false)
                btn_dlall.innerHTML = original_name
                return
            }
            let date_text = card.querySelector('h1.card-header').innerText

            // canvas的toBlob方法与async有兼容问题
            // 于是使用base64, 小图片还行, 大一点的文件就不行了
            let data = a_canvas.toDataURL('image/jpeg').replace(`data:image/jpeg;base64,`, '')
            zip.file(date_text.replace(' · ', '-') + '.jpg', data, { base64: true })
        }

        const content = await zip.generateAsync({ type: 'blob' })

        let url = URL.createObjectURL(content)
        let a = document.createElement('a')

        a.href = url
        a.download = zip_name

        a.click()
        URL.revokeObjectURL(url)

        setTimeout(() => {
            // 结束转圈
            btn_dlall.classList.toggle('disabled', false)
            btn_dlall.innerHTML = original_name
        }, 1000);
    }
    catch (e) {
        popup_msg('出错了', '下载错误, 请检查', e)
        btn_dlall.classList.toggle('disabled', false)
        btn_dlall.innerHTML = original_name
    }
}

async function if_save(btn) {
    if (btn.classList.contains('disabled')) return

    let first_date = my_cards[0].querySelector('h1.card-header').innerText.substring(0, 6)
    let last_date = my_cards[my_cards.length - 1].querySelector('h1.card-header').innerText.substring(0, 6)
    let zip_name = first_date + '-' + last_date + '_分享信息.zip'

    let a_dl = `<a style="font-size:1.2rem" href="javascript:save_all_cards('${zip_name}')">${zip_name}</a>`
    let arrow_down = '<span class="bi bi-arrow-down-circle"></span>'.repeat(3)
    popup_msg('请确认', '已将所有图片打包为zip压缩文档', `<strong>${arrow_down} 点击下方链接即可获得 ${arrow_down}</strong>`, a_dl)
}

async function copy_data(node) {
    if (node.classList.contains("disabled")) return;
    release_button();
    try {
        if (node['name'] === 'copytext') {

            let textbox_to_copy = node.parentElement;

            let header_ = textbox_to_copy.querySelector('h1.card-header').innerText;
            let title_ = textbox_to_copy.querySelector('div.card-title').innerText;
            let body_ = textbox_to_copy.querySelector('div.card-text').innerText;

            let card_text_ = `${title_}\n\n${header_}\n\n${body_}`;

            await navigator.clipboard.writeText(card_text_);
            node.innerHTML = '<span class="bi bi-card-text"></span> 已复制, 可在微信粘贴';
            node.classList.toggle("disabled", true);
        }
        else {
            let original_name = node.innerHTML
            node.classList.toggle("disabled", true);
            node.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 图片复制中...`
            let a_canvas = await get_canvas(node.parentElement)
            if (!a_canvas) {
                node.classList.toggle("disabled", false);
                node.innerHTML = original_name
                return
            }
            a_canvas.toBlob(copy_blob)

            setTimeout(() => node.innerHTML = '<span class="bi bi-image"></span> 已复制, 可在微信粘贴', 200)
            // node.innerHTML = '<span class="bi bi-image"></span> 已复制, 可在微信粘贴';
        }
    }
    catch (e) {
        console.error('Failed to copy: ', e)
        node.innerText = '复制失败'
        popup_msg('出错了', '复制图片失败', '可能是浏览器兼容性问题', e)
    }

}




